from base import BoxDriver, Logger, Yaml, Path, BoxRequest

__version__ = "2.0.1"
__author__ = "ArtLinty"


class _BasePage:
    _logger = None

    def __init__(self, logger=None):
        """
        构造方法
        :param logger:
        """
        self._logger = logger

    def log(self, msg):
        """
        记录日志
        :param msg:
        :return:
        """
        if self._logger and type(self._logger) == Logger:
            self._logger.info(msg)

    def config(self, file):
        """
        config
        :param file:
        :return:
        """
        if file and Path.file_is_exist(file):
            self.log("[system] - [%s] read config file: %s" % (__name__, file))
            return Yaml.get_config_as_dict(file)


class Page(_BasePage):
    """
    测试系统的最基础的页面类，是所有其他页面的基类
    """
    # 变量
    _driver = None

    # 方法
    def __init__(self, driver: BoxDriver, logger=None):
        """
        构造方法
        :param driver: 指定了参数类型，BoxDriver
        :param logger: 制定了
        """
        super(Page, self).__init__(logger)
        self._driver = driver
        self.log("[Page] - [%s] page initialized! " % __name__)

    def open(self, url):
        """
        打开页面
        :param url:
        :return:
        """
        self.driver.navigate(url)
        self.driver.maximize_window()
        self.driver.forced_wait(2)
        self.log("[Page] - [%s] page navigate: %s! " % (__name__, url))

    @property
    def current_url(self):
        """
        current url
        :return:
        """
        return self.driver.get_url()

    @property
    def title(self):
        """
        title
        :return:
        """
        return self.driver.get_title()

    @property
    def driver(self):
        """
        current driver
        :return:
        """
        return self._driver


class Api(_BasePage):
    _req = None
    _base_url = None

    def __init__(self, base_url, logger=None, auth=None, cookies=None):
        super(Api, self).__init__(logger)
        self._base_url = base_url
        self.log("[Api] - [%s] api initialized! " % __name__)

    @property
    def response(self):
        """
        get current response
        :return:
        """
        if self._req and isinstance(self._req, BoxRequest):
            return self._req.response

        return None

    def _parse_http_resp(self):
        """
        分析 http 的响应
        :return: 返回 dict
            status_code
            response_headers
            full_response
            json_dict
        """
        resp = {}
        if self._req and isinstance(self._req, BoxRequest):
            resp["status_code"] = self._req.status_code
            resp["response_headers"] = self._req.response_headers
            resp["full_response"] = self._req.response
            resp["json_dict"] = self._req.json_dict

        return resp
